package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.model.entity.BrowsingHistory;
import com.atguigu.lease.web.app.mapper.BrowsingHistoryMapper;
import com.atguigu.lease.web.app.service.BrowsingHistoryService;
import com.atguigu.lease.web.app.vo.history.HistoryItemVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author liubo
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {

	@Autowired
	private BrowsingHistoryMapper browsingHistoryMapper;

	@Override
	public IPage<HistoryItemVo> pageItemByUserId(Page<HistoryItemVo> page, Long userId) {
		return browsingHistoryMapper.pageItemByUserId(page,userId);
	}

	@Override
	// 设置方法异步操作，启动类上也要添加注解
	@Async
	public void saveHistory(Long userId, Long id) {
		// 测试异步生效
		// System.out.println("保存浏览历史-"+Thread.currentThread().getName());

		LambdaQueryWrapper<BrowsingHistory> queryWrapper = new LambdaQueryWrapper<>();
		// 查询用户id
		queryWrapper.eq(BrowsingHistory::getUserId, userId);
		// 查询房间id
		queryWrapper.eq(BrowsingHistory::getRoomId, id);
		// 查询
		BrowsingHistory browsingHistory = browsingHistoryMapper.selectOne(queryWrapper);

		// 数据库中是否用户已经查看的数据
		if (browsingHistory != null) {
			// 将当前数据的时间变为当前时间
			browsingHistory.setBrowseTime(new Date());
			// 更新时间
			browsingHistoryMapper.updateById(browsingHistory);
		} else {
			BrowsingHistory history = new BrowsingHistory();
			history.setUserId(userId);
			history.setRoomId(id);
			history.setCreateTime(new Date());
			// 插入用户访问记录
			browsingHistoryMapper.insert(history);
		}
	}
}